package freespiritsocial.io.user.ui.fragment.search

import android.os.Bundle
import androidx.core.widget.addTextChangedListener
import com.scwang.smart.refresh.layout.util.SmartUtil.dp2px
import freespiritsocial.io.user.R
import freespiritsocial.io.user.base.BaseFragment
import freespiritsocial.io.user.databinding.FrgSearchTagBinding
import freespiritsocial.io.user.decoration.SpaceItemDecoration
import freespiritsocial.io.user.ext.*
import freespiritsocial.io.user.handle.BackHandle
import freespiritsocial.io.user.ui.adapter.SearchTagAdapter
import freespiritsocial.io.user.viewmodel.SearchTagViewModel
import me.hgj.jetpackmvvm.ext.nav

/**
 * @description 編輯帖子搜索tag
 */
class SearchTagFrg: BaseFragment<SearchTagViewModel,FrgSearchTagBinding>() {
    private val adapter by lazy(LazyThreadSafetyMode.NONE) {
        SearchTagAdapter().apply {
            setOnItemClickListener { _,_,position ->
                addTag(data[position].tagName ?: return@setOnItemClickListener)
            }
        }
    }

    override fun layoutId(): Int = R.layout.frg_search_tag

    override fun initView(savedInstanceState: Bundle?) = with(mDatabind) {
        model = mViewModel
        click = Click()
        recyclerResult.init(adapter,hasEmpty = false)
            .addItemDecoration(SpaceItemDecoration(0,dp2px(15f)))
        etSearch.addTextChangedListener {
            if (it?.length == 0) {
                mViewModel.search()
                etSearch.setText("#")
                etSearch.setSelection(1)
                showLoading()
                return@addTextChangedListener
            }
            adapter.boldText = it.toString()
            mViewModel.search()
            adapter.clearData()
            if (it?.isEmpty() == true) adapter.notifyDataSetChanged()
        }
        root.setTitle(getString(R.string.tag_people))
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        showLoading()
        mDatabind.etSearch.setText("#")
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.searchResultNetWork.observe(this) {
            dismissLoading()
            if (it != null)
                adapter.addData(it)
            else
                adapter.notifyDataSetChanged()
        }
    }

    fun addTag(tag: String) {
        if (tag.isEmpty()) return
        eventViewModel.tagSelectEvent.postValue(tag)
        nav().navigateUp()
    }

    inner class Click: BackHandle {
        override fun goBack() {
            nav().navigateUp()
        }

        fun addTag() {
            val tag = mViewModel.searchText.value
            this@SearchTagFrg.addTag(tag)
        }

        fun removeSearch() {
            mViewModel.searchText.value = ""
            adapter.clearData()
        }
    }
}